$(document).ready(function(){
    /* 类别 */
    fillCategories();

    verify();

    initRelationBook();

    $(".searchBooks>button").on("click", function() {
        let param = $(this).siblings("input").val();
        searchBooks = searchBook(param);
        localStorage.setItem("searchBooks", JSON.stringify(searchBooks));
        location.href="bookList?categoryName=";
    });
    $("li.loginout").click(function() {
        $.removeCookie("userAccount");
        location.reload();
    });
})

let collectionBooks = null;
let cartBooks = null;
let searchBooks = null;
var reg = new RegExp("\"", "g");

/* 获取购物车订单的模板 */
function getCartBookTemplate(book) {
    return "<li class='minicart-item_area'>" +
        "<div class='minicart-single_item'>" +
        "<div class='product-item_remove'>" +
        "<span class='ion-android-close' title='" + book.bookIsbn +"' storeId='" + book.storeId + "'></span>" +
        "</div>" +
        "<div class='minicart-img'>" +
        "<a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" +
        "<img src='..//..//images//" + book.img.replace(reg, "") + "' alt='" + book.bookName +"'>" +
        "</a>" +
        "</div>" +
        "<div class='minicart-content'>" +
        "<div class='product-name'>" +
        "<h6>" +
        "<a href='bookDetails?bookIsbn=" + book.bookIsbn + "'>" + book.bookName + "</a>" +
        "</h6>" +
        "</div>" +
        "<span class='product-quantity'>数量:" + book.num + "</span>" +
        "<div class='price-box'>" +
        "<span class='new-price'>￥" + book.bookPrice + "</span>" +
        "</div>" +
        "</div>" +
        "</div>" +
        "</li>";
}

function getRelationBooks(relation) {
    let books = [];
    let formData = new FormData();
    formData.append("relation",relation);
    // formData.append("pageNum",1);
    // formData.append("pageSize",4);
    $.ajax({
        type: "post",
        url: "/api/relationBook/u/getRelationBookByUserRelation",
        dataType: "text",
        async: false,
        data: formData,
        processData : false,
        contentType : false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                books = JSON.parse(data.data);
            }else {
                // alert(data.msg);
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
    return books;
}

function initRelationBook() {
    collectionBooks = getRelationBooks("COLLECT");
    cartBooks = getRelationBooks("CART");
    $(".cart>ul.minicart-body").empty();
    cartBooks.forEach(book => {
        $(".cart>ul.minicart-body").append(getCartBookTemplate(book));
    });
    $(".cart>a>div.minicart-icon>span.item-count").text(cartBooks.length);
    $(".cart>ul.minicart-body li span.ion-android-close").on("click", function() {
        let isbn = $(this).attr("title");
        let storeId = $(this).attr("storeId");
        if (deleteRelation(storeId, isbn, "购物车")) {
            initRelationBook();
        }
    });
    $(".collection>a>div.minicart-icon>span.item-count").text(collectionBooks.length);
}

function deleteRelation(storeId, isbn, relation) {
    let result = false;
    $.ajax({
        type: "post",
        url: "/api/userBookRelation/u/deleteRelation",
        dataType: "text",
        async: false,
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            "relation": relation,
            "bookIsbn": isbn,
            "storeId": storeId
        }),
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                console.log(data.msg);
                updateRecommendBooks();
                result = true;
            }else {
                console.log(data.msg);
                result = false;
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    })
    return result;
}

//获得一级类别
function getFirstCategory() {
    var result;
    $.ajax({
        type: "get",
        url: "/api/category/v/getFisrtCategory",
        async: false,
        processData: false,
        contentType: false,
        success: data => {
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

//根据类名获得子类
function getChildrenCategoryByName(name) {
    var result;
    var formData = new FormData();
    formData.append("name", name);
    $.ajax({
        type: "post",
        url: "/api/category/v/getChildrenCategoryByName",
        async: false,
        dataType: "text",
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

function fillCategories() {
    var firstCategories = getFirstCategory();
    var str = "";
    firstCategories.forEach((item, index) => {
        if (item!=="" && item!==null) {
            if (index%2 === 0) {
                str = str.concat(item.categoryName);
            }else {
                str = str.concat("/");
                str = str.concat(item.categoryName);
                str = str.concat(",");
            }
        }
    });
    var categoriesList = str.split(",");
    str = "";
    //遍历一级类别
    categoriesList.forEach((item) => {
        if (item !== "" && item !== null) {
            var tmp = item.split("/");
            var firstChildrenCategory;
            var secondChildrenCategory;
            //二级类别
            firstChildrenCategory = getChildrenCategoryByName(tmp[0]);
            secondChildrenCategory = getChildrenCategoryByName(tmp[1]);
            str = str.concat("<li class='right-menu'><a href='javaScript: void(0);'>" + item + "</a><ul class='cat-mega-menu'>");
            //遍历二级类别
            if (firstChildrenCategory.length!==0) {
                str = str.concat("<li class='right-menu cat-mega-title'><a href='bookList?categoryName=" + tmp[0] + "'>" + tmp[0] + "</a><ul>");
                firstChildrenCategory.forEach(firstItem => {
                    str = str.concat("<li><a href='bookList?categoryName=" + firstItem.categoryName + "'>" + firstItem.categoryName + "</a></li>");
                });
                str = str.concat("</ul></li>");
            }
            //遍历二级类别
            if (secondChildrenCategory.length!==0) {
                str = str.concat("<li class='right-menu cat-mega-title'><a href='bookList?categoryName=" + tmp[1] + "'>" + tmp[1] + "</a><ul>");
                secondChildrenCategory.forEach(secondItem => {
                    str = str.concat("<li><a href='bookList?categoryName=" + secondItem.categoryName + "'>" + secondItem.categoryName + "</a></li>");
                });
                str = str.concat("</ul></li>");
            }
            str = str.concat("</ul></li>");
        }
    })
    $(".category-menu-list>ul").append(str);
}

/* 判断用户是否登录 */
function verify() {
    if ($.cookie("userAccount") === null || typeof($.cookie("userAccount")) === "undefined") {
        $("div.login-area").show();
    }else {
        $("div.login-area").hide();
    }
}

//搜索书籍
function searchBook(param) {
    let result;
    let formData = new FormData();
    formData.append("param", param);
    $.ajax({
        type: "post",
        url: "/api/book/v/searchBooks",
        async: false,
        dataType: "text",
        data: formData,
        processData: false,
        contentType: false,
        success: data => {
            data = eval('('+ data +')');
            if (data.success) {
                result = JSON.parse(data.data);
            }else {
                result = [];
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            const msg = xhr.responseText;
            console.log(msg);
        }
    });
    return result;
}

function updateRecommendBooks() {
        let result;
        $.ajax({
            type: "get",
            url: "/api/recommendBook/u/updateRecommendBooks",
            dataType: "text",
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    result = JSON.parse(data.data);
                }else {
                    result = [];
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
        return result;
}